package com.ts.proj.json;

import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.FileEntity;
import com.ts.proj.entity.InformationEntity;
import com.ts.proj.entity.ProjectMeetingEntity;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.entity.excelEntity.InformationEntityExcel;
import com.ts.proj.service.FileService;
import com.ts.proj.service.InformationService;
import com.ts.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class InfoJson extends BaseController {

    @Autowired
    private InformationService informationService;

    @Autowired
    private FileService fileService;

    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/info-list/{page}/{size}/{id}")
    public Map<String,Object> financeList(@PathVariable("page") Integer page, @PathVariable("size") Integer size,@PathVariable("id") Integer id){

        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");

        //用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());
        pageData.put("proID", id);

        long count = informationService.count(pageData);
        List<InformationEntity> finances = informationService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", finances);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/info-ins-upd-del")
    public Object financeInsUpdDel(){
        PageData pageData = this.getPageData();
        SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
        if(null!=pageData.get("id")&&!"".equals(pageData.get("id").toString())){
            Integer id = -1;
            //修改
            if(null!=pageData.get("id")&&!"".equals(pageData.get("id").toString())){
                id = Integer.valueOf(pageData.get("id").toString());
            }
            InformationEntity informationEntity = null;
            informationEntity = informationService.findById(id);

            //删除
            if(null!=pageData.get("deleteflag")&&!"".equals(pageData.get("deleteflag").toString())){
                //根据file的doc_type可以查出所有相关联file（th_zt_meet_[meetid]）
                PageData pageData1 = new PageData();
                pageData1.put("deleteflag", "N");
                pageData1.put("docType", "th_zt_info_"+informationEntity.getId());
                List<FileEntity> fileEntityList = fileService.findAll(pageData1);
                for(FileEntity fileEntity : fileEntityList) {
                    String path = locaionPre;
                    path += fileEntity.getUuid() + split + fileEntity.getState()
                            + split + fileEntity.getState() + "_" + fileEntity.getProjName();
                    fileEntity.setDeleteFlag("Y");
                    fileService.save(fileEntity);
                    File localFile = new File(path);
                    localFile.delete();
                }
                informationEntity.setDeleteFlag(pageData.get("deleteflag").toString());
            }
            if(null!=pageData.get("state")&&!"".equals(pageData.get("state").toString())){
                informationEntity.setState(pageData.get("state").toString());
            }
            if(null!=pageData.get("descValue")&&!"".equals(pageData.get("descValue").toString())){
                informationEntity.setDescValue(pageData.get("descValue").toString());
            }

            if(null!=pageData.get("proID")&&!"".equals(pageData.get("proID").toString())){
                informationEntity.setProID(Integer.valueOf(pageData.get("proID").toString()));
            }
            informationEntity.setUserId(systemUserEntity.getId());
            informationEntity.setBelongTo(systemUserEntity.getBelongTo());
            informationService.save(informationEntity);
        }
        return "success";
    }

    @RequestMapping("/info-download")
    public void export(HttpServletResponse response){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<InformationEntity> entitys = informationService.findAll(param);
        List<InformationEntityExcel> excelEntities = new ArrayList<>();
        for(InformationEntity tempEntity :entitys){
            InformationEntityExcel excel = new CopyObjectEntity2EntityExcel<InformationEntityExcel, InformationEntity>().copy(InformationEntityExcel.class,InformationEntity.class,tempEntity);
            excelEntities.add(excel);
        }
        EasyPoiUtil.exportExcel(excelEntities,"","",InformationEntityExcel.class, DateUtil.getID()+".xls",response);
    }


    @RequestMapping("/project-info-count/{id}")
    public long projectPeopleInfoCount(@PathVariable("id") Integer id){
        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("proID", id);
        return informationService.count(pd);
    }
}
